package com.gzz.demo.crypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.util.Base64;

public class DES {
    private final byte[] desKey;

    public DES(String desKey) {
        this.desKey = desKey.getBytes();
    }

    public static void main(String[] args) throws Exception {
        String key = "BBDmwTjBsF7IwTIyGWt1bmFn";
        String input = "a";
        DES crypt = new DES(key);
        System.out.println("Encode:" + crypt.encrypt(input));

    }

    public byte[] desEncrypt(byte[] plainText) throws Exception {
        String alg = "DESede";
        byte[] rawKeyData = desKey;
        //DESKeySpec dks = new DESKeySpec(rawKeyData);
        DESedeKeySpec dks = new DESedeKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg);
        SecretKey secretKey = keyFactory.generateSecret(dks);


        Cipher cipher = Cipher.getInstance(alg);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] data = plainText;
        byte[] encryptedData = cipher.doFinal(data);
        return encryptedData;
    }

    public String encrypt(String input) throws Exception {
        return Base64.getDecoder().decode(desEncrypt(input.getBytes())).toString();
    }
}
